package com.devinlee.msg.config;

import com.devinlee.msg.properties.MsgProperties;
import com.devinlee.msg.service.MsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自动配置类
 * <p>
 * 自动配置类的全路径需配置在META-INF\spring.factories下
 * Created by devinlee in 2021.11.04
 */
@Configuration
@ConditionalOnClass(MsgService.class)//MsgService类名在类路径上存在，才实例化当前Bean
@EnableConfigurationProperties(MsgProperties.class)//开启@ConfigurationProperties注解
public class MsgAutoConfiguration {

    /**
     * 注入属性配置类
     */
    @Autowired
    private MsgProperties msgProperties;

    @Bean
    @ConditionalOnMissingBean(MsgService.class)
    @ConditionalOnProperty(prefix = "msg", value = "enabled", havingValue = "true")//当msg.enabled=true才初始化这个bean
    public MsgService msgService() {
        MsgService msgService = new MsgService(msgProperties.getUrl(), msgProperties.getAccessKeyId(),
                msgProperties.getAccessKeySecret());
        // 如果提供了其他set方法，在此也可以调用对应方法对其进行相应的设置或初始化。
        return msgService;
    }
}
